<?php
/**
 * Notes:
 * Created by PhpStorm.
 * Author: TS
 * Date: 2019/10/26
 * Time: 9:37
 */

namespace app\admin\controller;

use app\model\Departments as DepartmentModel;
use app\model\Users as UsersModel;

class Department
{
    public function getAllDepartment(){
        if(request()->isPost()){
            $DepartmentModel = new DepartmentModel();
            $res_data = $DepartmentModel->getAllDepartment();
            return res(1,'',$res_data);
        }
        return res(0,MSG_NOT_POST);
    }

    public function addDepartment(){
        if(request()->isPost()){
            $data = request()->only('user_id,department_name,department_info');
            $UserModel = new UsersModel();
            $checkUser = $UserModel->checkHas($data['user_id']);
            if($checkUser == null) return res(0,'用户不存在');
            $DepartmentModel = new DepartmentModel();
            $check_department_name = $DepartmentModel->check($data['department_name']);
            if($check_department_name != null) return res(0,'已存在同名部门');
            $data['create_time'] = time();
            $add_res = $DepartmentModel->addDepartment($data);
            if($add_res){
                return res(1,'添加成功');
            }
            return res(0,'添加失败');
        }
        return res(0,MSG_NOT_POST);
    }
    public function editDepartment(){
        if(request()->isPost()){
            $data = request()->only('user_id,department_name,department_info');
            $department_id = input('department_id');
            $DepartmentModel = new DepartmentModel();
            $edit_res = $DepartmentModel->edit($department_id,$data);
            if($edit_res){
                return res(1,'修改成功');
            }
            return res(0,'修改失败');
        }
        return res(0,MSG_NOT_POST);
    }
    public function delDepartment(){
        if(request()->isPost()){
            $department_id = input('department_id');
            $UserModel = new UsersModel();
            $department_num = $UserModel->checkDepartment($department_id);
            if($department_num > 0) return res(0,'无法删除，该部门下还有' . $department_num . '个人');
            $DepartmentModel = new DepartmentModel();
            $check_has = $DepartmentModel->checkHas($department_id);
            if($check_has == null) return res(0,'无该部门');
            $del_res = $DepartmentModel->delDepartment($department_id);
            if($del_res){
                return res(1,'删除成功');
            }
            return res(0,'删除失败');
        }
        return res(0,MSG_NOT_POST);
    }

}